<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        class HashTable {
            storage = []
            count = 0
            limit = 7
            // 哈希函数： 生成字符串在数组中存储的下标, 质数一般选择37
            hashFun (str, limit) {
                let hashcode = 0
                for(let i=0; i<str.length; i++) {
                    hashcode = hashcode * 37 + str.charCodeAt(i)
                }
                // console.log(hashcode)
                hashcode =  hashcode % limit
                return hashcode
            }

            // 插入或者修改
            put(key, value){
                let index = this.hashFun(key, this.limit)
                let bucket = this.storage[index]
                if (bucket == null) {
                    bucket = []
                    this.storage[index] = bucket
                }

                for(let i=0; i<bucket.length; i++) {
                    let tuple = bucket[i]
                    if (tuple[0] === key) {
                        tuple[1] = value
                        return
                    }
                }
                bucket.push([key, value])
            }
        }

        let hash = new HashTable()
        let a = hash.hashFun('abc', 7)
        let b = hash.hashFun('bba', 7)
        let c = hash.hashFun('aab', 7)
        let d = hash.hashFun('ccd', 7)

        hash.put('name', 'mystic')
        console.log(a,b,c,d)
        console.log(hash)
    </script>
</body>
</html>